<?php
namespace app\common\model\newmodel;

use think\Model;
use think\Db;
use app\common\model\newmodel\UserAgency;
use app\common\model\newmodel\User as UserModel;

class Customer extends Model
{
    protected $table = 'customer';
    protected $pk = 'CustomerId';
    
    const ISAGENT_YES = 1; //属于代理商
    const ISAGENT_No  = 0; //不属于代理商

    public function agentInfo()
    {
        return $this->belongsTo('app\\common\\model\\newmodel\\User', 'AgentId', 'UserId')->field('UserId,Name');
    }

    /**
     * 获取客户列表（根据用户角色权限）
     * @param int $userId 当前用户ID
     * @param int $page 页码
     * @param int $pageSize 每页数量
     * @param string $keyword 搜索关键词
     * @return array
     */
    public static function getCustomerList($state='', $userId, $page = 1, $pageSize = 10, $keyword = '')
    {
        if (empty($userId)) {
            return ['code' => 0, 'msg' => '用户ID不能为空'];
        }
        
        $user = UserModel::get($userId);
        if (!$user) {
            return ['code' => 0, 'msg' => '用户不存在'];
        }
        
        $role = $user->Role;
        $query = self::with(['agentInfo']);
        
        if ($role == 201) {
            // 业务员 - 可以看到所有不属于代理商的客户
            $query->where('LatestAgentId',0);
        } elseif ($role == 401) {
            // 代理商管理员 - 可以看到同组管理的代理商的所有客户
            $agencyId = UserAgency::getAgencyIdByUserId($userId);
            $userIds=UserAgency::getUserIdsByAgencyId($agencyId);
            if (!$agencyId) {
                return ['code' => 0, 'msg' => '未绑定代理商'];
            }
            $query->whereIn('LatestAgentId', $userIds);
        } elseif ($role == 402) {
            // 代理商员工 - 只能看到自己的客户
            $agencyId = UserAgency::getAgencyIdByUserId($userId);
            if (!$agencyId) {
                return ['code' => 0, 'msg' => '未绑定代理商'];
            }
            $query->where('LatestAgentId', $userId);
        } else {
            return ['code' => 0, 'msg' => '无权限访问客户列表'];
        }
        
        if (!empty($keyword)) {
            $query=$query->where(function ($q) use ($keyword) {
                $q->where('Name', 'like', "%{$keyword}%")
                  ->whereOr('Tel', 'like', "%{$keyword}%")
                  ->whereOr('UserName', 'like', "%{$keyword}%");
            });
        }
        
        $list = $query
                    ->order('CustomerId desc')
                    ->paginate([
                        'list_rows' => $pageSize,
                        'page' => $page
                    ]);
        
        $data = $list->toArray();
        $data['status']= [-1 => '全部客户', 3 => '一般客户', 1 => '目标客户', 11 => '重点目标客户', 2 => '跟进中', 12 => '重点跟进', 99 => '已成交', 404 => '无效'];
        return ['code' => 1, 'msg' => 'success', 'data' => $data];
    }
    /**
     * 添加客户
     */
    public static function addCustomer($data)
    {
        if (empty($data['UserName']) || empty($data['Tel'])) {
            return ['code' => 0, 'msg' => '客户名称和电话不能为空'];
        }
        
        $existTel = self::where('Tel', $data['Tel'])
                       ->find();
        if ($existTel) {
            return ['code' => 0, 'msg' => '客户电话已存在'];
        }
        
        $customer = new self();
        $customer->Name = $data['Name'] ?? '';
        $customer->Address = $data['Address'] ?? '';
        $customer->Tel = $data['Tel'] ?? '';
        $customer->OtherTel = $data['OtherTel'] ?? '';
        $customer->UserName = $data['UserName'] ?? '';
        $customer->UserTel = $data['UserTel'] ?? '';
        $customer->Type = $data['Type'] ?? '';
        $customer->Scale = $data['Scale'] ?? '';
        $customer->Note = $data['Note'] ?? '';
        $customer->Source = $data['Source'] ?? '';
        $customer->LicenseNumber = $data['LicenseNumber'] ?? '';
        $customer->StreetId = $data['StreetId'] ?? null;
        $customer->IsAgent = $data['IsAgent'] ?? self::ISAGENT_No;
        $customer->LatestAgentId = $data['LatestAgentId'] ?? null;
        $customer->BussinessId = $data['BussinessId'] ?? null;
        $customer->AddTime = date('Y-m-d H:i:s');
        $customer->LastTime = date('Y-m-d H:i:s');
        $customer->isPlanform = $data['isPlanform'] ?? null;
        $customer->RobatMap = $data['RobatMap'] ?? null;
        $customer->Img = $data['Img'] ?? '';
        $customer->OperationLog = $data['OperationLog'] ?? '';
        $customer->AppointmentTime = date('Y-m-d H:i:s'); 
        $customer->Visitingtime = date('Y-m-d H:i:s');
        $customer->BindTime = date('Y-m-d H:i:s');
        $customer->Lat = $data['Lat'] ?? null;
        $customer->Lon = $data['Lon'] ?? null;

        if ($customer->save()) {
            return ['code' => 1, 'msg' => '客户添加成功', 'data' => $customer];
        } else {
            return ['code' => 0, 'msg' => '客户添加失败'];
        }
    }

    /**
     * 编辑客户信息
     */
    public static function editCustomer($data)
    {
        if (empty($data['CustomerId']) || empty($data['UserName']) || empty($data['Tel'])) {
            return ['code' => 0, 'msg' => '客户ID、名称和电话不能为空'];
        }
        
        $customer = self::get($data['CustomerId']);
        if (!$customer) {
            return ['code' => 0, 'msg' => '客户不存在'];
        }
        
        // 检查电话是否与其他客户重复
        $existTel = self::where('Tel', $data['Tel'])
                       ->where('CustomerId', '<>', $data['CustomerId'])
                       ->find();
        if ($existTel) {
            return ['code' => 0, 'msg' => '客户电话已存在'];
        }
        
        $customer->Name = $data['Name'] ?? $customer->Name;
        $customer->Address = $data['Address'] ?? $customer->Address;
        $customer->Tel = $data['Tel'];
        $customer->State = $data['State'] ?? $customer->State;
        $customer->OtherTel = $data['OtherTel'] ?? $customer->OtherTel;
        $customer->UserName = $data['UserName'] ?? $customer->UserName;
        $customer->UserTel = $data['UserTel'] ?? $customer->UserTel;
        $customer->Type = $data['Type'] ?? $customer->Type;
        $customer->Scale = $data['Scale'] ?? $customer->Scale;
        $customer->Note = $data['Note'] ?? $customer->Note;
        $customer->Source = $data['Source'] ?? $customer->Source;
        $customer->LicenseNumber = $data['LicenseNumber'] ?? $customer->LicenseNumber;
        $customer->Lon = $data['Lon'] ?? $customer->Lon;
        $customer->Lat = $data['Lat'] ?? $customer->Lat;
        $customer->CompanyId = $data['CompanyId'] ?? $customer->CompanyId;
        $customer->BussinessId = $data['BussinessId'] ?? $customer->BussinessId;
        $customer->StreetId = $data['StreetId'] ?? $customer->StreetId;
        $customer->IsAgent = $data['IsAgent'] ?? $customer->IsAgent;
        $customer->AgentId = $data['AgentId'] ?? $customer->AgentId;
        $customer->isPlanform = $data['isPlanform'] ?? $customer->isPlanform;
        $customer->RobatMap = $data['RobatMap'] ?? $customer->RobatMap;
        $customer->Img = $data['Img'] ?? $customer->Img;
        $customer->OperationLog = $data['OperationLog'] ?? $customer->OperationLog;
        $customer->AppointmentTime = $data['AppointmentTime'] ?? $customer->AppointmentTime;
        $customer->Visitingtime = $data['Visitingtime'] ?? $customer->Visitingtime;
        $customer->BindTime = $data['BindTime'] ?? $customer->BindTime;
        
        if ($customer->save()) {
            return ['code' => 1, 'msg' => '客户信息修改成功', 'data' => $customer];
        } else {
            return ['code' => 0, 'msg' => '客户信息修改失败'];
        }
    }

    public static function ChangeAgency($user_id,$customer_id)
    {
        $customer=Customer::get($customer_id);
        if(!$customer){
            return ['code' => 0, 'msg' => '客户不存在'];
        }
        $customer->AgentId=$user_id;
        $customer->IsAgent=1;
        $customer->save();
        return [
            'code' =>1,
            'message'=>'分配成功'
        ];
    }
}
